Linear search
依陣列中第一個元素開始依序查詢符合的數值。
Input: nums = [3, 9, 8, 2, 1], key = 8
let lineSearch = (nums, target) => {
if (!nums) return -1
for (let i = 0; i < nums.length; i++) {
if (nums[i] === target) return i
}
}
console.log(lineSearch([3, 9, 8, 2, 1], 8))
Output: 2
Flow Chart:
Input: nums = [3, 9, 8, 2, 1]
nums[i], target =>
1. (3 !== 8) i++
2. (9 !== 8) i++
3. (8 === 8)
return i //2